package controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"wish_go/src/main/com/ajie/common"
	"wish_go/src/main/com/ajie/dao"
	"wish_go/src/main/com/ajie/model"
	"wish_go/src/main/com/ajie/result"
)

var (
	baseUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
)

func MiniLogin(req *gin.Context) {
	var wxLogin model.WxLogin
	code, b := req.GetQuery("code")
	if !b {
		result.Error(req, 500, "CODE不能为空")
		return
	}
	appid := viper.GetString("mini.appid")
	secret := viper.GetString("mini.secret")
	// 构建url
	url := fmt.Sprintf(baseUrl, appid, secret, code)
	// 向微信发送请求
	requestCode, resultByte := common.GetRequest(url)
	if requestCode != 200 {
		result.Error(req, 500, "请求异常")
		return
	}
	if len(resultByte) == 0 {
		result.Error(req, 500, "请求结果异常")
		return
	}
	jsonErr := json.Unmarshal(resultByte, &wxLogin)
	if jsonErr != nil {
		result.Error(req, 500, "json解析异常："+jsonErr.Error())
		return
	}
	// 保存用户信息
	dbErr := dao.InsertMini(model.User{Openid: wxLogin.OpenId})
	if dbErr != nil {
		result.Error(req, 500, "服务器异常："+dbErr.Error())
		return
	}
	result.SuccessData(req, "登陆成功", wxLogin)
}

func GetUserInfo(req *gin.Context) {
	openid := req.Param("openid")
	db := common.GetDB()
	user, userErr := dao.GetUser(db, model.User{Openid: openid})
	if userErr != nil {
		result.Error(req, 500, "用户获取异常："+userErr.Error())
		return
	}
	result.SuccessData(req, "获取成功", user)
}

func UpdateUserInfo(req *gin.Context) {
	var user model.User
	if jsonErr := req.BindJSON(&user); jsonErr != nil {
		result.Error(req, 500, "参数解析异常："+jsonErr.Error())
		return
	}
	i, userErr := dao.UpdateMiniUser(user)
	if userErr != nil {
		result.Error(req, 500, "更新异常："+userErr.Error())
		return
	}
	if i < 1 {
		result.Error(req, 500, "更新失败")
		return
	}
	result.Success(req, "更新成功")
}
